'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Progress } from '@/components/ui/progress'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { 
  IconRefresh,
  IconTrash,
  IconClock,
  IconCheck,
  IconX,
  IconLoader,
  IconChevronRight,
  IconFilter,
  IconSearch
} from '@tabler/icons-react'
import { Input } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { api, type TaskStatus, type QueueStats } from '@/lib/api'
import { toast } from 'sonner'
import AuthGuard from '@/components/AuthGuard'

export default function TasksPage() {
  const [queueStats, setQueueStats] = useState<QueueStats | null>(null)
  const [tasks, setTasks] = useState<TaskStatus[]>([])
  const [filteredTasks, setFilteredTasks] = useState<TaskStatus[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [statusFilter, setStatusFilter] = useState<string>('all')
  const [selectedTasks, setSelectedTasks] = useState<string[]>([])

  // 定期刷新数据
  useEffect(() => {
    const fetchData = async () => {
      try {
        const [statsData, historyData] = await Promise.all([
          api.tasks.getQueueStats(),
          api.tasks.getHistory(100, 0)
        ])
        
        setQueueStats(statsData)
        setTasks(historyData.tasks || [])
        setIsLoading(false)
      } catch (error) {
        console.error('获取数据失败:', error)
        toast.error('获取数据失败')
        setIsLoading(false)
      }
    }

    fetchData()
    
    // 每5秒刷新一次
    const interval = setInterval(fetchData, 5000)
    return () => clearInterval(interval)
  }, [])

  // 过滤任务
  useEffect(() => {
    let filtered = tasks

    // 状态过滤
    if (statusFilter !== 'all') {
      filtered = filtered.filter(task => task.status === statusFilter)
    }

    // 搜索过滤
    if (searchTerm) {
      filtered = filtered.filter(task => 
        task.task_id.toLowerCase().includes(searchTerm.toLowerCase())
      )
    }

    setFilteredTasks(filtered)
  }, [tasks, statusFilter, searchTerm])

  const handleRefresh = async () => {
    setIsLoading(true)
    try {
      const [statsData, historyData] = await Promise.all([
        api.tasks.getQueueStats(),
        api.tasks.getHistory(100, 0)
      ])
      
      setQueueStats(statsData)
      setTasks(historyData.tasks || [])
      toast.success('数据已刷新')
    } catch (error) {
      toast.error('刷新失败')
    } finally {
      setIsLoading(false)
    }
  }

  const handleCancelTasks = async () => {
    if (selectedTasks.length === 0) {
      toast.error('请先选择要取消的任务')
      return
    }

    try {
      await api.tasks.cancelTask(selectedTasks)
      toast.success(`已取消 ${selectedTasks.length} 个任务`)
      setSelectedTasks([])
      handleRefresh()
    } catch (error) {
      toast.error('取消任务失败')
    }
  }

  const handleClearCache = async () => {
    try {
      await api.tasks.clearCache()
      toast.success('缓存已清理')
      handleRefresh()
    } catch (error) {
      toast.error('清理缓存失败')
    }
  }

  const toggleTaskSelection = (taskId: string) => {
    setSelectedTasks(prev => 
      prev.includes(taskId) 
        ? prev.filter(id => id !== taskId)
        : [...prev, taskId]
    )
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed': return 'bg-green-100 text-green-800'
      case 'running': return 'bg-blue-100 text-blue-800'
      case 'pending': return 'bg-yellow-100 text-yellow-800'
      case 'failed': return 'bg-red-100 text-red-800'
      case 'cancelled': return 'bg-gray-100 text-gray-800'
      default: return 'bg-gray-100 text-gray-800'
    }
  }

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'completed': return <IconCheck size={16} />
      case 'running': return <IconLoader size={16} className="animate-spin" />
      case 'pending': return <IconClock size={16} />
      case 'failed': return <IconX size={16} />
      case 'cancelled': return <IconX size={16} />
      default: return <IconClock size={16} />
    }
  }

  const formatDuration = (timestamp?: number) => {
    if (!timestamp) return '-'
    const duration = Date.now() - timestamp
    if (duration < 60000) return `${Math.round(duration / 1000)}秒`
    if (duration < 3600000) return `${Math.round(duration / 60000)}分钟`
    return `${Math.round(duration / 3600000)}小时`
  }

  const getStatusText = (status: string) => {
    const statusMap = {
      'completed': '已完成',
      'running': '运行中',
      'pending': '等待中',
      'failed': '失败',
      'cancelled': '已取消'
    }
    return statusMap[status as keyof typeof statusMap] || status
  }

  if (isLoading && !queueStats) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <IconLoader size={48} className="animate-spin mx-auto text-blue-600 mb-4" />
          <p className="text-gray-600">加载任务数据中...</p>
        </div>
      </div>
    )
  }

  return (
    <AuthGuard>
      <div className="min-h-screen bg-gray-50 p-6">
      <div className="max-w-7xl mx-auto space-y-6">
        {/* 面包屑 */}
        <div className="flex items-center space-x-2 text-sm text-gray-500">
          <span>医疗数字孪生</span>
          <IconChevronRight size={16} />
          <span className="text-blue-600">任务管理</span>
        </div>

        {/* 页面标题 */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-gray-900">任务管理中心</h1>
            <p className="text-gray-600 mt-1">监控和管理AI处理任务队列</p>
          </div>
          <div className="flex space-x-2">
            <Button onClick={handleClearCache} variant="outline">
              🧹 清理缓存
            </Button>
            <Button onClick={handleRefresh} disabled={isLoading}>
              <IconRefresh size={16} className={isLoading ? 'animate-spin' : ''} />
              刷新
            </Button>
          </div>
        </div>

        {/* 队列统计 */}
        {queueStats && (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <Card>
              <CardContent className="p-4">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600">总任务数</p>
                    <p className="text-2xl font-bold">{queueStats.total_tasks}</p>
                  </div>
                  <div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
                    <span className="text-blue-600 text-sm">📊</span>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-4">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600">运行中</p>
                    <p className="text-2xl font-bold text-blue-600">{queueStats.running_tasks}</p>
                  </div>
                  <div className="w-8 h-8 bg-blue-100 rounded-lg flex items-center justify-center">
                    <IconLoader size={16} className="text-blue-600 animate-spin" />
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-4">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600">等待中</p>
                    <p className="text-2xl font-bold text-yellow-600">{queueStats.pending_tasks}</p>
                  </div>
                  <div className="w-8 h-8 bg-yellow-100 rounded-lg flex items-center justify-center">
                    <IconClock size={16} className="text-yellow-600" />
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardContent className="p-4">
                <div className="flex items-center justify-between">
                  <div>
                    <p className="text-sm text-gray-600">缓存命中率</p>
                    <p className="text-2xl font-bold text-green-600">
                      {(queueStats.cache_hit_rate * 100).toFixed(1)}%
                    </p>
                  </div>
                  <div className="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center">
                    <span className="text-green-600 text-sm">💾</span>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        )}

        {/* 任务列表 */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle>任务列表</CardTitle>
                <CardDescription>AI处理任务历史记录</CardDescription>
              </div>
              {selectedTasks.length > 0 && (
                <Button onClick={handleCancelTasks} variant="destructive" size="sm">
                  <IconTrash size={16} className="mr-1" />
                  取消选中任务 ({selectedTasks.length})
                </Button>
              )}
            </div>
          </CardHeader>
          <CardContent>
            {/* 过滤器 */}
            <div className="flex items-center space-x-4 mb-6">
              <div className="flex-1">
                <div className="relative">
                  <IconSearch size={16} className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" />
                  <Input
                    placeholder="搜索任务ID..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-9"
                  />
                </div>
              </div>
              <Select value={statusFilter} onValueChange={setStatusFilter}>
                <SelectTrigger className="w-32">
                  <IconFilter size={16} className="mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="running">运行中</SelectItem>
                  <SelectItem value="pending">等待中</SelectItem>
                  <SelectItem value="completed">已完成</SelectItem>
                  <SelectItem value="failed">失败</SelectItem>
                  <SelectItem value="cancelled">已取消</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 任务列表 */}
            <div className="space-y-3">
              {filteredTasks.length === 0 ? (
                <div className="text-center py-12 text-gray-500">
                  <IconClock size={48} className="mx-auto mb-4 text-gray-300" />
                  <p>暂无任务数据</p>
                </div>
              ) : (
                filteredTasks.map((task) => (
                  <div
                    key={task.task_id}
                    className="flex items-center justify-between p-4 border rounded-lg hover:bg-gray-50 transition-colors"
                  >
                    <div className="flex items-center space-x-4">
                      <input
                        type="checkbox"
                        checked={selectedTasks.includes(task.task_id)}
                        onChange={() => toggleTaskSelection(task.task_id)}
                        className="w-4 h-4 text-blue-600 rounded focus:ring-blue-500"
                      />
                      
                      <div className="flex items-center space-x-3">
                        <div className={`flex items-center space-x-1 px-2 py-1 rounded-full text-xs ${getStatusColor(task.status)}`}>
                          {getStatusIcon(task.status)}
                          <span>{getStatusText(task.status)}</span>
                        </div>
                        
                        <div>
                          <p className="font-medium font-mono text-sm">{task.task_id}</p>
                          <p className="text-xs text-gray-500">
                            创建时间: {new Date(task.created_at).toLocaleString('zh-CN')}
                          </p>
                        </div>
                      </div>
                    </div>

                    <div className="flex items-center space-x-6">
                      {/* 进度条 */}
                      {task.status === 'running' && (
                        <div className="w-32">
                          <div className="flex justify-between text-xs mb-1">
                            <span>进度</span>
                            <span>{Math.round(task.progress * 100)}%</span>
                          </div>
                          <Progress value={task.progress * 100} className="h-1" />
                        </div>
                      )}

                      {/* 持续时间 */}
                      <div className="text-right">
                        <p className="text-sm text-gray-600">
                          {task.status === 'running' ? '运行时长' : '总时长'}
                        </p>
                        <p className="text-xs text-gray-500">
                          {formatDuration(task.started_at || task.created_at)}
                        </p>
                      </div>

                      {/* 错误信息 */}
                      {task.error && (
                        <div className="max-w-xs">
                          <p className="text-xs text-red-600 truncate" title={task.error}>
                            {task.error}
                          </p>
                        </div>
                      )}
                    </div>
                  </div>
                ))
              )}
            </div>
          </CardContent>
        </Card>
        </div>
      </div>
    </AuthGuard>
  )
} 